import React, { useState } from 'react';
import { Form, Input, Button, Upload, message } from 'antd';
import { UserOutlined, MailOutlined, LockOutlined, UploadOutlined } from '@ant-design/icons';
import './login.css';
import {register} from '../../../api/user'
import {useNavigate} from 'react-router-dom'
import service from '../../../utils/request'

export default function Login() {
    const navigate=useNavigate()
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [form] = Form.useForm();
    const [avatarUrl, setAvatarUrl] = useState('https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=150&h=150&fit=crop&crop=face');


    const handleAvatarChange = (info: any) => {
        if (info.file.status === 'done') {
            // info.file.response 可能是完整URL或仅包含相对路径
            const resp = info.file.response || {};
            const rawUrl: string = resp.url || '';
            const base = (service.defaults.baseURL as string) || (import.meta.env.VITE_API_URL as string) || 'http://localhost:3001';
            const finalUrl = /^https?:\/\//i.test(rawUrl) ? rawUrl : `${base}${rawUrl}`;
            setAvatarUrl(finalUrl);
            message.success('头像上传成功！');
        }
    };

    // 注册
    const handleRegister=()=>{
        register({
            img:avatarUrl,
            username:name,
            email:email,
            password:password
        })
        .then(response=>{
           console.log(response)
           if(response.success){
            setName('')
            setEmail('')
            setPassword('')
            navigate('/')

           }
        })

    }

    const customUpload = async ({ file, onSuccess, onError }: any) => {
        try {
            const formData = new FormData();
            formData.append('avatar', file as File);
            const res = await service.post('/user/upload/avatar', formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });
            if (res.data && res.data.success) {
                const base = (service.defaults.baseURL as string) || (import.meta.env.VITE_API_URL as string) || 'http://localhost:3001';
                const rawUrl: string = res.data.data?.url || '';
                const fullUrl = /^https?:\/\//i.test(rawUrl) ? rawUrl : `${base}${rawUrl}`;
                setAvatarUrl(fullUrl);
                onSuccess?.({ url: fullUrl });
                message.success('头像上传成功！');
            } else {
                throw new Error(res.data?.message || '上传失败');
            }
        } catch (e: any) {
            message.error(e.message || '上传失败');
            onError?.(e);
        }
    }

    return (
        <div className="login-container">

            <div className="login-form-container">
                <div className="login-form">
                    <h1 className="login-title">协同云</h1>

                    <div className="avatar-section">
                        <div className="avatar-container">
                            <img src={avatarUrl} alt="Avatar" className="avatar-image" />
                        </div>
                        <Upload
                            name="avatar"
                            showUploadList={false}
                            onChange={handleAvatarChange}
                            customRequest={customUpload}
                        >
                            <Button type="link" className="upload-button">
                                上传头像
                            </Button>
                        </Upload>
                    </div>

                    <Form
                        form={form}
                        name="login"
                        layout="vertical"
                        className="form"
                    >
                        <Form.Item
                            name="username"
                            rules={[{ required: true, message: '请输入用户名！' }]}
                        >
                            <Input
                                prefix={<UserOutlined />}
                                placeholder="请输入用户名"
                                className="form-input"
                                size="large"
                                value={name}
                                onChange={(e)=>setName(e.target.value)}
                            />
                        </Form.Item>

                        <Form.Item
                            name="email"
                            rules={[
                                { required: true, message: '请输入邮箱！' },
                                { type: 'email', message: '请输入有效的邮箱地址！' }
                            ]}
                        >
                            <Input
                                prefix={<MailOutlined />}
                                placeholder="请输入邮箱"
                                className="form-input"
                                size="large"
                                value={email}
                                onChange={(e)=>setEmail(e.target.value)}
                            />
                        </Form.Item>

                        <Form.Item
                            name="password"
                            rules={[{ required: true, message: '请输入密码！' }]}
                        >
                            <Input.Password
                                prefix={<LockOutlined />}
                                placeholder="请输入密码"
                                className="form-input"
                                size="large"
                                value={password}
                                onChange={(e)=>setPassword(e.target.value)}
                            />
                        </Form.Item>

                        <Form.Item>
                            <Button
                                type="primary"
                                htmlType="submit"
                                className="signup-button"
                                size="large"
                                onClick={handleRegister}
                            >
                                注册
                            </Button>
                        </Form.Item>
                    </Form>
                    {/* 底部选项 */}
                    <div className="options-bottom">
                        <div className="center-options">
                            <a href="/" className="option-link">登录账号</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}